package com.yj.web.util;

import com.yj.web.WeChat.Base.WxException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * Created by yanlinyang on 2017/4/18.
 */
public class HttpUtil {
    private final  static String CharSet = "UTF-8";
    public static String doGet(String URL) throws WxException {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            HttpGet req = new HttpGet(URL);
            response = client.execute(req);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, CharSet);
        } catch (IOException e) {
            throw new WxException(e.getMessage());
        } finally {
            {
                try {
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (client != null) {
                        client.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    public static String doPost(String URL, String body) throws WxException {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            HttpPost req = new HttpPost(URL);
            req.setEntity(new StringEntity(body, CharSet));
            response = client.execute(req);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, CharSet);
        } catch (IOException e) {
            throw new WxException(e.getMessage());
        } finally {
            {
                try {
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (client != null) {
                        client.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
